const path = require('path')
const fs = require('fs')
// Postcss 插件
const PostcssPxToViewport = require('postcss-px-to-viewport')
const PostcssNormalize = require('postcss-normalize')
// 客制化
const {
  override,
  addWebpackAlias,
  addPostcssPlugins,
  addBabelPlugins,
  addBundleVisualizer,
  adjustStyleLoaders,
  addWebpackModuleRule,
  useEslintRc,
} = require('customize-cra')

// 修改devtool配置
const updateDevelopmentTool = () => (config) => {
  config.devtool = 'cheap-module-eval-source-map'
  return config
}

// split npm modules
const customOptimizationSplitChunks = () => (config) => {
  Object.assign(config.output, {
    chunkFilename: '[name].[contenthash:8].js',
  })
  Object.assign(config.optimization.splitChunks, {
    chunks: 'all',
    maxInitialRequests: Infinity,
    minChunks: 2,
    minSize: 12288,
    cacheGroups: {
      vendor: {
        test: /[\\/]node_modules[\\/]/,
        priority: 20,
        minSize: 40960,
        enforce: true,
        name(module) {
          const packageName = module.context.match(/[\\/]node_modules[\\/](.*?)([\\/]|$)/)[1]
          let fileName = packageName.replace('@', '').split('@')[0]
          return `package~${fileName}`
        },
      },
    },
  })
  return config
}

module.exports = {
  webpack: override(
    useEslintRc(path.resolve(__dirname, './.eslintrc.json')),
    // 添加路径别名配置
    addWebpackAlias({
      '@': path.join(__dirname, './src'),
    }),
    // 支持 babel-polyfill 按需自动导入
    addBabelPlugins(['@babel/plugin-transform-runtime', { corejs: { version: 3 } }]),
    // 添加 Postcss 配置
    addPostcssPlugins([
      PostcssPxToViewport({
        viewportWidth: 375, // 视图大小
        viewportUnit: 'vw', // 视图单位
        unitToConvert: 'px', // 需转换的单位
        unitPrecision: 3, // 转换后小数点位数
      }),
      PostcssNormalize({
        forceImport: 'sanitize.css',
      }),
    ]),
    adjustStyleLoaders((rule) => {
      if (rule.test.toString().includes('scss')) {
        rule.use.push({
          loader: require.resolve('sass-resources-loader'),
          options: {
            resources: [path.resolve(__dirname, './src/assets/scss/index.scss')],
          },
        })
      }
    }),
    // icon svg 方案
    addWebpackModuleRule({
      test: /\.svg$/,
      include: [path.resolve(__dirname, './src/assets/icons')],
      use: [
        {
          loader: 'svg-sprite-loader',
          options: { symbolId: 'icon-[name]' },
        },
        // 对svg定制化
        {
          loader: 'svgo-loader',
        },
      ],
    }),
    updateDevelopmentTool(),
    customOptimizationSplitChunks(),
    addBundleVisualizer(
      {
        analyzerMode: 'static',
        reportFilename: 'report.html',
      },
      true,
    ),
  ),
  paths: (paths, env) => {
    // 打包时修改默认输出路径以及资源前置路径
    if (env === 'production') {
      console.info(`=> production APP:${process.env.REACT_APP_CODE}<=`)
      console.info(`=> ENV:${process.env.REACT_APP_ENV || '根据域名确定'}  <=`)

      paths.publicUrlOrPath = './'
      paths.appBuild = path.resolve(__dirname, 'dist')
    }
    if (process.env.REACT_APP_CODE === 'tiya') {
      paths.appHtml = path.resolve(__dirname, 'public/tiya_index.html')
    } else {
      paths.appHtml = path.resolve(__dirname, 'public/zy_index.html')
    }
    return paths
  },
}
